package com.peanut.baby.comm;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.Advice;
import com.peanut.baby.model.InitialAdTK;
import com.peanut.baby.model.MyTag;
import com.peanut.baby.model.UStatus;
import com.peanut.baby.mvp.dingyue.DingyueContract;
import com.peanut.baby.mvp.dingyue.DingyuePresenter;
import com.peanut.baby.mvp.dingyue.DingyueTagAdapter;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.AppUtil;
import com.peanut.baby.util.PrefUtil;
import com.peanut.baby.widget.NoLineClickSpan;
import com.peanut.devlibrary.BaseActivity;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.SysUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.tencent.mars.xlog.Log;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.carbswang.android.numberpickerview.library.NumberPickerView;

public class DingyueDialog implements OnClickListener,DingyueTagAdapter.OnitemClickedListener{
    TagFlowLayout tagHotLayout;
    TagFlowLayout tagRecommendLayout;
    TagFlowLayout tagAlreadyLayout;


    TextView subscribe;
    ImageView close;

    TextView refresh;

    private List<String> tagsHot;
    private DingyueTagAdapter hotAdapter;

    private List<String> tagsRecommend;
    private DingyueTagAdapter rmdAdapter;

    private List<String> tagsSubscribe;
    private DingyueTagAdapter subscribeAdapter;
    Dialog dialog;
    Activity context;
    Window window;
    private DingyuePresenter presenter;
    public DingyueDialog() {

    }



    public Dialog showDingyueDialog(final Activity context) {

        if (context instanceof Activity && ((Activity) context).isFinishing()) {
            return null;
        }
        this.context = context;
        dialog = new Dialog(context,R.style.dialog_full_width);
        dialog.setContentView(R.layout.activity_dingyue);
        dialog.show();
        window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;

//        params.width = (int) (context.getResources().getDisplayMetrics().widthPixels  * 0.9);
//        params.height = (int) (context.getResources().getDisplayMetrics().heightPixels * 0.8);
        // 这里还可以设置lp.x，lp.y在x轴，y轴上的坐标，只是这个位置是基于Gravity的
        window.setAttributes(params);

        window.setContentView(R.layout.activity_dingyue);

        tagHotLayout = window.findViewById(R.id.tag_hot);
        tagRecommendLayout = window.findViewById(R.id.tag_recommend);
        tagAlreadyLayout = window.findViewById(R.id.tag_subscribed);

        subscribe = window.findViewById(R.id.subscribe);
        close = window.findViewById(R.id.dingyue_close);

        refresh = window.findViewById(R.id.dingyue_refresh);

        refresh.setOnClickListener(this);
        close.setOnClickListener(this);
        subscribe.setOnClickListener(this);
        tagsHot = new ArrayList<>();
        tagsRecommend = new ArrayList<>();
        tagsSubscribe = new ArrayList<>();

        hotAdapter = new DingyueTagAdapter(context,DingyueTagAdapter.SET_HOT,tagsHot);
        rmdAdapter = new DingyueTagAdapter(context,DingyueTagAdapter.SET_RECOMMEND,tagsRecommend);
        subscribeAdapter = new DingyueTagAdapter(context,DingyueTagAdapter.SET_SUBSCRIBED,tagsSubscribe);


        tagHotLayout.setAdapter(hotAdapter);
        tagRecommendLayout.setAdapter(rmdAdapter);
        tagAlreadyLayout.setAdapter(subscribeAdapter);

        hotAdapter.setListener(this);
        rmdAdapter.setListener(this);
        subscribeAdapter.setListener(this);

        subscribe.setOnClickListener(this);


        presenter = new DingyuePresenter(context, new DingyueContract.View() {
            @Override
            public void onHotTagsGet(boolean success, List<String> tags, String failReason) {
                if(success && tags != null){
                    if(tags != null && !tags.isEmpty()){
                        tagsHot.clear();
                        tagsHot.addAll(tags);
                        hotAdapter.notifyDataChanged();
                        tagHotLayout.requestLayout();
                    }
                }else{
                    Toast.makeText(context,failReason,Toast.LENGTH_LONG).show();

                }
            }

            @Override
            public void onRecommendTagsGet(boolean success, MyTag tags, String failReason) {
                if(success && tags != null){
                    onMyTagGet(tags);
                }else{
                    Toast.makeText(context,failReason,Toast.LENGTH_LONG).show();

                }
            }

            @Override
            public void onSubscribeResult(boolean success) {
                Toast.makeText(context,"订阅"+(success? "成功":"失败"),Toast.LENGTH_SHORT).show();
                if(success){
                    dismissDialog(dialog);
                }
            }
        });

        savePref();
        presenter.getRecommendTags();
        return dialog;
    }

    private void savePref(){
        PrefUtil.saveLong(AppConfig.PrefConfig.PREF_LAST_DINGYUE_POP,System.currentTimeMillis());
        String monthlyDingyueCountKey = "monthlyDingyueCountKey_"+ TimeUtil.getCurrentDate();
        int count = PrefUtil.getIntDefaultZero(monthlyDingyueCountKey);

        PrefUtil.saveInt(monthlyDingyueCountKey,count+1);
    }

    void onMyTagGet(MyTag myTags){
        if(myTags.hot != null && !myTags.hot.isEmpty()){
            tagsHot.clear();
            tagsHot.addAll(myTags.hot);
            hotAdapter.notifyDataChanged();
        }
        if(myTags.rem != null && !myTags.rem.isEmpty()){
            window.findViewById(R.id.dingyue_rmd_label).setVisibility(View.VISIBLE);
            tagsRecommend.clear();
            tagsRecommend.addAll(myTags.rem);
            rmdAdapter.notifyDataChanged();
        }else{
            window.findViewById(R.id.dingyue_rmd_label).setVisibility(View.GONE);
        }

        if(myTags.my != null && !myTags.my.isEmpty()){
            tagsSubscribe.clear();
            tagsSubscribe.addAll(myTags.my);
            subscribeAdapter.notifyDataChanged();
        }


    }


    /**
     * 取消dialog
     *
     * @param dialog
     */
    private void dismissDialog(Dialog dialog) {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.dingyue_refresh:
                presenter.getHotTags();
                break;
            case R.id.subscribe:
                subscribe();
                break;
            case R.id.dingyue_close:
                dismissDialog(dialog);
                break;
        }
    }

    private void subscribe(){
        String result  = prepareSubscribeTag();
        if(StringUtil.isNullOrEmpty(result)){
            Toast.makeText(context,"请选择订阅的标签",Toast.LENGTH_SHORT).show();
            return;
        }
        presenter.subscribeTags(result);
    }
    private String prepareSubscribeTag(){
        StringBuffer sb = new StringBuffer();
        if(tagsSubscribe != null && !tagsSubscribe.isEmpty()){
            for(int i=0;i<tagsSubscribe.size();i++){
                sb.append(tagsSubscribe.get(i));
                sb.append(",");
            }
        }
        return sb.toString();
    }

    @Override
    public void OnitemClicked(int setType, int index) {
        switch(setType){
            case DingyueTagAdapter.SET_HOT:
                String tag = tagsHot.remove(index);
                tagsSubscribe.add(tag);
                hotAdapter.notifyDataChanged();
                subscribeAdapter.notifyDataChanged();
                break;
            case DingyueTagAdapter.SET_RECOMMEND:
                tagsRecommend.remove(index);
                rmdAdapter.notifyDataChanged();
                break;
            case DingyueTagAdapter.SET_SUBSCRIBED:
                tagsSubscribe.remove(index);
                subscribeAdapter.notifyDataChanged();

                break;
        }
    }
}
